<template>
  <div class="enterprise-center" :key="animationKey">
    <!-- 左侧导航栏 -->
    <EnterpriseSidebar />

    <!-- 右侧主内容区域 -->
    <main class="main-content">
      <!-- 顶部操作栏 -->
      <div class="top-header">
        <div class="header-left">
          <h2 class="page-title">{{ $t('enterpriseMessageCenter.pageTitle') }}</h2>
          <div class="header-stats">
            <span class="unread-count-info">
              {{ $t('enterpriseMessageCenter.unreadMessages') }}: <el-tag type="warning" size="small">{{ messageCategories.find(cat => cat.id === 'unread')?.unreadCount || 0 }}</el-tag>
            </span>
            <span class="user-type-info">
              <el-tag type="success" size="small">{{ $t('enterpriseMessageCenter.enterpriseUser') }}</el-tag>
            </span>
          </div>
        </div>
        <div class="header-actions">
          <el-button 
            size="small" 
            type="info" 
            @click="refreshMessages"
            :loading="loading"
            :disabled="loading"
          >
            <el-icon v-if="!loading"><Refresh /></el-icon>
            {{ loading ? $t('enterpriseMessageCenter.refreshing') : $t('enterpriseMessageCenter.refresh') }}
          </el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="markAllAsRead"
            :disabled="!messageCategories.find(cat => cat.id === 'unread')?.unreadCount"
          >
            <el-icon><Check /></el-icon>
            {{ $t('enterpriseMessageCenter.markAllAsRead') }}
            <el-badge 
              v-if="messageCategories.find(cat => cat.id === 'unread')?.unreadCount" 
              :value="messageCategories.find(cat => cat.id === 'unread')?.unreadCount" 
              class="button-badge"
            />
          </el-button>
          <el-button size="small" type="danger" @click="clearAllMessages">
            {{ $t('enterpriseMessageCenter.clearAllMessages') }}
          </el-button>
        </div>
      </div>

      <!-- 消息分类和列表区域 -->
      <div class="message-section">
      <!-- 消息分类 -->
      <div class="message-categories">
        <h4 class="category-title">{{ $t('enterpriseMessageCenter.messageCategories') }}</h4>
        <div class="category-description">
          <el-alert
            :title="$t('enterpriseMessageCenter.permissionTitle')"
            :description="$t('enterpriseMessageCenter.permissionDescription')"
            type="info"
            :closable="false"
            show-icon
            size="small"
          />
        </div>
        <div class="category-list">
          <div 
            v-for="category in messageCategories" 
            :key="category.id"
            class="category-item"
            :class="{ active: activeCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <span class="category-name">{{ category.name }}</span>
            <el-badge 
              v-if="category.unreadCount > 0" 
                :value="category.unreadCount" 
              class="unread-badge"
            />
          </div>
        </div>
      </div>

        <!-- 消息列表 -->
        <div class="message-list">
          <div class="list-header">
            <h3 class="list-title">{{ $t('enterpriseMessageCenter.messageList') }}</h3>
            <div class="list-info">
              <span class="message-count">{{ $t('enterpriseMessageCenter.totalMessages', { total: pagination.total }) }}</span>
              <span v-if="lastRefreshTime" class="refresh-time">
                {{ $t('enterpriseMessageCenter.lastRefresh') }}: {{ formatTime(lastRefreshTime) }}
              </span>
            </div>
          </div>
          
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <el-icon class="is-loading" size="24"><Loading /></el-icon>
            <p>{{ $t('enterpriseMessageCenter.loading') }}</p>
          </div>
          
          <!-- 消息列表 -->
          <div v-else class="message-items">
            <div 
              v-for="message in filteredMessages" 
              :key="message.notificationId"
              class="message-item"
              :class="{ unread: !message.isRead }"
              @click="selectMessage(message)"
            >
              <div class="message-indicator">
                <div 
                  class="status-dot"
                  :class="getStatusClass(message.messageType)"
                ></div>
              </div>
              <div class="message-content">
                <div class="message-title">{{ message.title || $t('enterpriseMessageCenter.noTitle') }}</div>
                <div class="message-type">{{ getMessageTypeName(message.messageType) }}</div>
                <div class="message-time">{{ formatTime(message.sentTime) }}</div>
              </div>
            </div>
            
            <!-- 空状态 -->
            <div v-if="filteredMessages.length === 0" class="empty-message">
              <el-icon size="48" color="#ccc"><Message /></el-icon>
              <p>{{ $t('enterpriseMessageCenter.noMessages') }}</p>
            </div>
          </div>
          
          <!-- 分页 -->
          <div v-if="pagination.totalPages > 1" class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.page"
              :page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </main>

    <!-- 消息详情弹框 -->
    <el-dialog
      v-model="messageDialogVisible"
      :title="selectedMessage?.title || $t('enterpriseMessageCenter.messageDetail')"
      width="600px"
      :before-close="handleCloseDialog"
      class="message-detail-dialog"
    >
      <div v-if="selectedMessage" class="message-detail-content">
        <div class="message-meta">
          <span class="message-type">{{ $t('enterpriseMessageCenter.messageType') }}: {{ getMessageTypeName(selectedMessage.messageType) }}</span>
          <span class="time">{{ $t('enterpriseMessageCenter.time') }}: {{ formatTime(selectedMessage.sentTime) }}</span>
          <span class="status" :class="{ unread: !selectedMessage.isRead }">
            {{ selectedMessage.isRead ? $t('enterpriseMessageCenter.read') : $t('enterpriseMessageCenter.unread') }}
          </span>
        </div>
        
        <div class="message-body">
          <!-- 加载状态 -->
          <div v-if="selectedMessage.loading" class="message-loading">
            <el-icon class="is-loading" size="20"><Loading /></el-icon>
            <span>{{ $t('enterpriseMessageCenter.loadingMessageDetail') }}</span>
          </div>
          
          <!-- 消息内容 -->
          <div v-else class="message-content-detail">
            <div class="message-title-detail">
              <h3>{{ selectedMessage.title || $t('enterpriseMessageCenter.noTitleDetail') }}</h3>
            </div>
            <div class="message-text">
              <div v-html="safeMessageContent"></div>
            </div>
          </div>
          
          <div class="message-footer">
            <p class="platform-signature">{{ $t('enterpriseMessageCenter.platformSignature') }}</p>
            <p class="message-id">{{ $t('enterpriseMessageCenter.messageId') }}: {{ selectedMessage.notificationId || $t('enterpriseMessageCenter.unknown') }}</p>
          </div>
        </div>
          </div>
          
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="messageDialogVisible = false">{{ $t('enterpriseMessageCenter.close') }}</el-button>
          <el-button 
            v-if="!selectedMessage?.isRead"
            type="success" 
            @click="markCurrentMessageAsRead"
          >
            <el-icon><Check /></el-icon>
            {{ $t('enterpriseMessageCenter.markAsRead') }}
          </el-button>
          <el-button type="danger" @click="deleteMessage(selectedMessage?.notificationId)">
            <el-icon><Delete /></el-icon>
            {{ $t('common.delete') }}
          </el-button>
          <el-button type="primary" @click="replyMessage(selectedMessage?.notificationId)">
            <el-icon><ChatDotRound /></el-icon>
            {{ $t('common.reply') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { 
  Message, ChatDotRound, Loading, Check, Refresh, Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { enterpriseMessageApi, MESSAGE_TYPES, MESSAGE_STATUS, MESSAGE_PRIORITY } from '../../api/enterprise.js'
import EnterpriseSidebar from '../../components/EnterpriseSidebar.vue'

// 国际化
const { t, locale } = useI18n()

// 强制重新渲染的key
const animationKey = ref(0)

// 响应式数据
const activeCategory = ref('all')
const selectedMessage = ref(null)
const messageDialogVisible = ref(false)
const loading = ref(false)
const messages = ref([])
const lastRefreshTime = ref(null)
const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
  totalPages: 0
})

// 简单的HTML内容安全处理函数
const sanitizeHtml = (html) => {
  if (!html) return '';
  
  // 创建一个临时的div元素来解析HTML
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  
  // 移除潜在的危险标签和属性
  const scripts = tempDiv.querySelectorAll('script');
  scripts.forEach(script => script.remove());
  
  // 移除所有on*事件处理器属性
  const allElements = tempDiv.getElementsByTagName('*');
  for (let i = 0; i < allElements.length; i++) {
    const element = allElements[i];
    const attributes = element.attributes;
    
    for (let j = attributes.length - 1; j >= 0; j--) {
      const attrName = attributes[j].name;
      if (attrName.startsWith('on') || attrName === 'href' && attributes[j].value.startsWith('javascript:')) {
        element.removeAttribute(attrName);
      }
    }
  }
  
  return tempDiv.innerHTML;
}

// 获取安全处理后的消息内容
const safeMessageContent = computed(() => {
  if (!selectedMessage.value || !selectedMessage.value.content) {
    return t('enterpriseMessageCenter.noContentDetail');
  }
  return sanitizeHtml(selectedMessage.value.content);
})

// 未读数量存储
const unreadCounts = ref({
  all: 0,
  unread: 0,
  [MESSAGE_TYPES.ENTERPRISE_CERTIFICATION]: 0,
  [MESSAGE_TYPES.ENTERPRISE_CONTACT]: 0,
  [MESSAGE_TYPES.DEMAND_REVIEW]: 0,
  [MESSAGE_TYPES.MATCHING_SUCCESS]: 0,
  [MESSAGE_TYPES.ACCOUNT_DISABLED]: 0,
  [MESSAGE_TYPES.PASSWORD_CHANGE]: 0
})

// 消息分类 - 改为计算属性，响应语言变化
const messageCategories = computed(() => [
  { id: 'all', name: t('enterpriseMessageCenter.allMessages'), unreadCount: unreadCounts.value.all },
  { id: 'unread', name: t('enterpriseMessageCenter.unreadMessagesCategory'), unreadCount: unreadCounts.value.unread },
  { id: MESSAGE_TYPES.ENTERPRISE_CERTIFICATION, name: t('enterpriseMessageCenter.enterpriseCertification'), unreadCount: unreadCounts.value[MESSAGE_TYPES.ENTERPRISE_CERTIFICATION] },
  { id: MESSAGE_TYPES.ENTERPRISE_CONTACT, name: t('enterpriseMessageCenter.enterpriseContact'), unreadCount: unreadCounts.value[MESSAGE_TYPES.ENTERPRISE_CONTACT] },
  { id: MESSAGE_TYPES.DEMAND_REVIEW, name: t('enterpriseMessageCenter.demandReview'), unreadCount: unreadCounts.value[MESSAGE_TYPES.DEMAND_REVIEW] },
  { id: MESSAGE_TYPES.MATCHING_SUCCESS, name: t('enterpriseMessageCenter.matchingSuccess'), unreadCount: unreadCounts.value[MESSAGE_TYPES.MATCHING_SUCCESS] },
  { id: MESSAGE_TYPES.ACCOUNT_DISABLED, name: t('enterpriseMessageCenter.accountStatus'), unreadCount: unreadCounts.value[MESSAGE_TYPES.ACCOUNT_DISABLED] },
  { id: MESSAGE_TYPES.PASSWORD_CHANGE, name: t('enterpriseMessageCenter.passwordChange'), unreadCount: unreadCounts.value[MESSAGE_TYPES.PASSWORD_CHANGE] }
])

// 计算属性
const filteredMessages = computed(() => {
  if (activeCategory.value === 'all') {
    return messages.value
  } else if (activeCategory.value === 'unread') {
    return messages.value.filter(msg => !msg.isRead)
  } else {
    return messages.value.filter(msg => msg.messageType === activeCategory.value)
  }
})

// 方法
const getStatusClass = (messageType) => {
  // 如果消息类型为空或未定义，返回默认样式
  if (!messageType) {
    return 'info';
  }
  
  const classMap = {
    [MESSAGE_TYPES.ENTERPRISE_CERTIFICATION]: 'success', // 企业认证 - 绿色
    [MESSAGE_TYPES.ENTERPRISE_CONTACT]: 'info', // 企业联系 - 蓝色
    [MESSAGE_TYPES.DEMAND_REVIEW]: 'warning', // 需求审核 - 橙色
    [MESSAGE_TYPES.MATCHING_SUCCESS]: 'success', // 匹配成功 - 绿色
    [MESSAGE_TYPES.ACCOUNT_DISABLED]: 'danger', // 账户状态 - 红色
    [MESSAGE_TYPES.PASSWORD_CHANGE]: 'info' // 密码变更 - 蓝色
  }
  
  // 如果类型不在映射中，返回默认样式
  return classMap[messageType] || 'info';
}

// 获取消息列表
const fetchMessages = async (params = {}) => {
  try {
    loading.value = true
    
    const response = await enterpriseMessageApi.getMessages({
      page: pagination.value.page,
      size: pagination.value.size,
      messageType: activeCategory.value === 'all' || activeCategory.value === 'unread' ? '' : activeCategory.value,
      ...params
    })
    
    if (response && response.code === 200 && response.data) {
      // 确保messages是数组
      const messagesData = Array.isArray(response.data.messages) ? response.data.messages : []
      messages.value = messagesData
      
      // 更新分页信息
      pagination.value = {
        page: response.data.currentPage || 1,
        size: response.data.pageSize || 10,
        total: response.data.totalMessages || 0,
        totalPages: response.data.totalPages || 0
      }
      
      // 更新未读数量
      if (response.data.unreadCount !== undefined) {
        updateUnreadCount(response.data.unreadCount)
      } else {
        // 如果响应中没有未读数量，单独获取
        await fetchUnreadCount()
      }
      

    } else {
      messages.value = []
      handleApiError(response, '获取消息列表')
    }
  } catch (error) {
    messages.value = []
    handleNetworkError(error, '获取消息列表')
  } finally {
    loading.value = false
  }
}

// 更新未读数量
const updateUnreadCount = (unreadCount) => {
  // 更新未读消息的数量
  unreadCounts.value.unread = unreadCount
  messageCategories.value.find(cat => cat.id === 'all').unreadCount = unreadCount
  
  // 计算各分类的未读数量
  const categoryUnreadCounts = {}
  messages.value.forEach(message => {
    if (!message.isRead) {
      const categoryId = message.messageType
      categoryUnreadCounts[categoryId] = (categoryUnreadCounts[categoryId] || 0) + 1
    }
  })
  
  // 更新各分类的未读数量
  messageCategories.value.forEach(category => {
    if (category.id !== 'all' && category.id !== 'unread') {
      category.unreadCount = categoryUnreadCounts[category.id] || 0
    }
  })
}

// 统一处理API错误响应
const handleApiError = (response, operation) => {
  const errorCode = response?.code
  const errorMessage = response?.error || response?.message || '操作失败'
  
  switch (errorCode) {
    case 400:
      ElMessage.error(`${operation}失败: 请求参数错误 - ${errorMessage}`)
      break
    case 401:
      ElMessage.error(`${operation}失败: 身份验证失败，请重新登录`)
      // 可以在这里触发重新登录逻辑
      break
    case 403:
              ElMessage.error(`${operation}失败: ${t('enterpriseMessageCenter.accessDenied')}`)
      break
    case 404:
      ElMessage.error(`${operation}失败: 资源不存在`)
      break
    case 500:
      ElMessage.error(`${operation}失败: 服务器内部错误，请稍后重试`)
      break
    default:
      ElMessage.error(`${operation}失败: ${errorMessage}`)
  }
  

}

// 统一处理网络错误
const handleNetworkError = (error, operation) => {
  if (error.name === 'TypeError' && error.message.includes('fetch')) {
    ElMessage.error(`${operation}失败: 网络连接失败，请检查网络设置`)
  } else if (error.name === 'AbortError') {
    ElMessage.error(`${operation}失败: 请求被取消`)
  } else {
    ElMessage.error(`${operation}失败: ${error.message || '网络错误'}`)
  }
  

}

// 获取未读消息数量
const fetchUnreadCount = async () => {
  try {
    const response = await enterpriseMessageApi.getUnreadCount()
    
    if (response && response.code === 200 && response.data) {
      const unreadCount = response.data.unreadCount || 0
      updateUnreadCount(unreadCount)
    } else {
      // 如果获取失败，使用本地计算的数量
      const localUnreadCount = messages.value.filter(msg => !msg.isRead).length
      updateUnreadCount(localUnreadCount)
      
      handleApiError(response, '获取未读消息数量')
    }
  } catch (error) {
    // 如果获取异常，使用本地计算的数量
    const localUnreadCount = messages.value.filter(msg => !msg.isRead).length
    updateUnreadCount(localUnreadCount)
    
    handleNetworkError(error, '获取未读消息数量')
  }
}

// 清空所有消息
const clearAllMessages = async () => {
  try {
    await ElMessageBox.confirm(t('enterpriseMessageCenter.confirmClearAll'), t('enterpriseMessageCenter.confirmClear'), {
      confirmButtonText: t('enterpriseMessageCenter.confirm'),
      cancelButtonText: t('enterpriseMessageCenter.cancel'),
      type: 'warning'
    })
    
    // 调用清空消息的API
    await enterpriseMessageApi.clearAllMessages()
    
    ElMessage.success(t('enterpriseMessageCenter.messagesCleared'))
    messages.value = []
    selectedMessage.value = null
    
    // 重新获取消息列表
    await fetchMessages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('enterpriseMessageCenter.clearFailed') + ': ' + (error.message || '网络错误'))
    }
  }
}

// 消息分类选择
const selectCategory = async (categoryId) => {
  activeCategory.value = categoryId
  selectedMessage.value = null
  pagination.value.page = 1
  await fetchMessages()
}

// 消息选择 - 打开弹框并获取详情
const selectMessage = async (message) => {
  try {
    // 先显示加载状态
    selectedMessage.value = { ...message, loading: true }
    messageDialogVisible.value = true
    
    // 获取消息详情
    const response = await enterpriseMessageApi.getMessageDetail(message.notificationId)
    
    if (response && response.code === 200 && response.data) {
      selectedMessage.value = response.data
    } else {
      // 如果获取详情失败，使用列表中的基础信息
      selectedMessage.value = message
      const errorMsg = response?.message || '获取消息详情失败'
      ElMessage.warning(`${errorMsg}，显示基础信息`)

    }
    
    // 标记为已读
    if (!message.isRead) {
      try {
        const response = await enterpriseMessageApi.markMessageAsRead(message.notificationId)
        
        if (response && response.code === 200) {
          // 标记成功，更新本地状态
          message.isRead = true
          
          // 如果当前选中的消息是这条，也更新其状态
          if (selectedMessage.value && selectedMessage.value.notificationId === message.notificationId) {
            selectedMessage.value.isRead = true
          }
          
          // 重新获取未读数量
          await fetchUnreadCount()
          
          console.log('消息标记已读成功:', response.message)
        } else {
          // 标记失败，显示错误信息
          const errorMsg = response?.message || t('enterpriseMessageCenter.markAsReadFailed')
          ElMessage.warning(`${t('enterpriseMessageCenter.markAsReadFailed')}: ${errorMsg}`)
          console.warn('标记消息已读失败:', response)
        }
      } catch (error) {
        ElMessage.error(t('enterpriseMessageCenter.markAsReadFailed') + ': ' + (error.message || '网络错误'))
        console.error('标记消息已读异常:', error)
      }
    }
  } catch (error) {
    // 如果获取详情异常，使用列表中的基础信息
    selectedMessage.value = message
    ElMessage.warning(t('enterpriseMessageCenter.getMessageDetailFailed') + '，显示基础信息')
    
  }
}

// 关闭弹框
const handleCloseDialog = () => {
  messageDialogVisible.value = false
  selectedMessage.value = null
}

// 标记当前消息为已读
const markCurrentMessageAsRead = async () => {
  if (!selectedMessage.value || selectedMessage.value.isRead) {
    return
  }
  
  try {
    const response = await enterpriseMessageApi.markMessageAsRead(selectedMessage.value.notificationId)
    
    if (response && response.code === 200) {
      // 标记成功，更新本地状态
      selectedMessage.value.isRead = true
      
      // 更新列表中的消息状态
      const listMessage = messages.value.find(msg => msg.notificationId === selectedMessage.value.notificationId)
      if (listMessage) {
        listMessage.isRead = true
      }
      
      // 重新获取未读数量
      await fetchUnreadCount()
      
      ElMessage.success(t('enterpriseMessageCenter.messageMarkedAsRead'))
    } else {
      // 标记失败，显示错误信息
      const errorMsg = response?.message || t('enterpriseMessageCenter.markAsReadFailed')
      ElMessage.warning(`${t('enterpriseMessageCenter.markAsReadFailed')}: ${errorMsg}`)

    }
  } catch (error) {
    ElMessage.error(t('enterpriseMessageCenter.markAsReadFailed') + ': ' + (error.message || '网络错误'))
    
  }
}

// 删除单条消息
const deleteMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm(t('enterpriseMessageCenter.confirmDelete'), t('enterpriseMessageCenter.confirmDeleteTitle'), {
      confirmButtonText: t('enterpriseMessageCenter.confirm'),
      cancelButtonText: t('enterpriseMessageCenter.cancel'),
      type: 'warning'
    })
    
    await enterpriseMessageApi.deleteMessage(messageId)
    
    ElMessage.success(t('enterpriseMessageCenter.messageDeleted'))
    
    // 从本地列表中移除
    const index = messages.value.findIndex(msg => msg.notificationId === messageId)
    if (index > -1) {
      messages.value.splice(index, 1)
    }
    
    // 如果删除的是当前选中的消息，关闭弹框
    if (selectedMessage.value && selectedMessage.value.notificationId === messageId) {
      messageDialogVisible.value = false
      selectedMessage.value = null
    }
    
    // 重新获取消息列表以更新统计
    await fetchMessages()
    // 重新获取未读数量
    await fetchUnreadCount()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('enterpriseMessageCenter.deleteFailed') + ': ' + (error.message || '网络错误'))
    }
  }
}

// 回复消息
const replyMessage = (messageId) => {
  ElMessage.info(t('enterpriseMessageCenter.replyFeatureDeveloping'))
}

// 标记所有消息为已读
const markAllAsRead = async () => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(t('enterpriseMessageCenter.confirmMarkAllRead'), t('enterpriseMessageCenter.confirmOperation'), {
      confirmButtonText: t('enterpriseMessageCenter.confirm'),
      cancelButtonText: t('enterpriseMessageCenter.cancel'),
      type: 'info'
    })
    
    const response = await enterpriseMessageApi.markAllMessagesAsRead()
    
    if (response && response.code === 200) {
      // 更新本地消息状态
      messages.value.forEach(message => {
        message.isRead = true
      })
      
      // 如果当前有选中的消息，也更新其状态
      if (selectedMessage.value) {
        selectedMessage.value.isRead = true
      }
      
      // 重新获取未读数量
      await fetchUnreadCount()
      
      const totalMessages = messages.value.length
      ElMessage.success(t('enterpriseMessageCenter.allMessagesMarkedAsRead', { count: totalMessages }))
    } else {
      // 标记失败，显示错误信息
      const errorMsg = response?.message || t('enterpriseMessageCenter.markAllAsReadFailed')
      ElMessage.warning(`${t('enterpriseMessageCenter.markAllAsReadFailed')}: ${errorMsg}`)

    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('enterpriseMessageCenter.markAllAsReadFailed') + ': ' + (error.message || '网络错误'))

    }
  }
}

// 刷新消息列表
const refreshMessages = async () => {
  try {
    loading.value = true
    
    const response = await enterpriseMessageApi.refreshMessages()
    
    if (response && response.code === 200 && response.data) {
      // 更新消息列表
      const messagesData = Array.isArray(response.data.messages) ? response.data.messages : []
      messages.value = messagesData
      
      // 更新分页信息
      pagination.value = {
        page: response.data.currentPage || 1,
        size: response.data.pageSize || 20,
        total: response.data.totalMessages || 0,
        totalPages: response.data.totalPages || 0
      }
      
      // 更新未读数量
      if (response.data.unreadCount !== undefined) {
        updateUnreadCount(response.data.unreadCount)
      }
      
      // 更新最后刷新时间
      lastRefreshTime.value = response.refreshTime ? new Date(response.refreshTime) : new Date()
      
      // 显示刷新成功信息
      const refreshTime = response.refreshTime ? new Date(response.refreshTime).toLocaleString('zh-CN') : '刚刚'
      const newMessageCount = messagesData.length
      const unreadCount = response.data.unreadCount || 0
      
      ElMessage.success(t('enterpriseMessageCenter.refreshSuccess', { 
        newCount: newMessageCount, 
        unreadCount: unreadCount, 
        refreshTime: refreshTime 
      }))
    } else {
      // 处理不同的错误状态码
      handleApiError(response, '刷新消息列表')
    }
  } catch (error) {
    handleNetworkError(error, '刷新消息列表')
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) {
    return t('enterpriseMessageCenter.oneDayAgo')
  } else if (diffDays > 1) {
    return t('enterpriseMessageCenter.daysAgo', { days: diffDays })
  } else {
  return date.toLocaleString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
  }
}

// 获取消息类型名称
const getMessageTypeName = (messageType) => {
  if (!messageType) {
    return t('enterpriseMessageCenter.systemNotification');
  }
  
  const typeMap = {
    [MESSAGE_TYPES.ENTERPRISE_CERTIFICATION]: t('enterpriseMessageCenter.enterpriseCertification'),
    [MESSAGE_TYPES.ENTERPRISE_CONTACT]: t('enterpriseMessageCenter.enterpriseContact'),
    [MESSAGE_TYPES.DEMAND_REVIEW]: t('enterpriseMessageCenter.demandReview'),
    [MESSAGE_TYPES.MATCHING_SUCCESS]: t('enterpriseMessageCenter.matchingSuccess'),
    [MESSAGE_TYPES.ACCOUNT_DISABLED]: t('enterpriseMessageCenter.accountStatus'),
    [MESSAGE_TYPES.PASSWORD_CHANGE]: t('enterpriseMessageCenter.passwordChange')
  }
  
  return typeMap[messageType] || t('enterpriseMessageCenter.systemNotification');
}

// 分页处理
const handleSizeChange = async (size) => {
  pagination.value.size = size
  pagination.value.page = 1
  await fetchMessages()
}

const handleCurrentChange = async (page) => {
  pagination.value.page = page
  await fetchMessages()
}

// 语言初始化
const initLanguage = () => {
  const savedLang = localStorage.getItem('lang')
  if (savedLang && ['zh', 'en'].includes(savedLang)) {
    locale.value = savedLang
  }
}

// 语言变化事件处理
const handleLanguageChange = (event) => {
  const { language } = event.detail
  // 强制重新渲染组件以更新语言
  animationKey.value++
}

// 组件挂载
onMounted(async () => {
  // 初始化语言设置
  initLanguage()
  
  // 监听语言变化事件
  window.addEventListener('languageChanged', handleLanguageChange)
  
  await fetchMessages()
  // 确保获取未读数量
  await fetchUnreadCount()
  // 设置初始刷新时间
  lastRefreshTime.value = new Date()
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener('languageChanged', handleLanguageChange)
})
</script>

<style scoped>
.enterprise-center {
  display: flex;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 右侧主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 顶部操作栏 */
.top-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background-color: white;
  border-bottom: 1px solid #e9ecef;
}

.header-left .page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.header-stats {
  display: flex;
  align-items: center;
  gap: 15px;
}

.unread-count-info {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-type-info {
  font-size: 12px;
  color: #666;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  position: relative;
}

.button-badge {
  position: absolute;
  top: -8px;
  right: -8px;
}

/* 消息分类和列表区域 */
.message-section {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
}

/* 消息分类 */
.message-categories {
  width: 250px;
  background-color: white;
  padding: 20px;
  height: fit-content;
}

.category-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
}

.category-description {
  margin-bottom: 20px;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.category-item:hover {
  background-color: #f8f9fa;
}

.category-item.active {
  background-color: #e3f2fd;
  color: #1976d2;
  border-color: #1976d2;
  font-weight: 500;
}

.category-name {
  font-size: 14px;
}

.unread-badge {
  margin-left: 8px;
}

/* 消息列表 */
.message-list {
  flex: 1;
  background-color: white;
  padding: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
}

.list-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.list-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.message-count {
  font-weight: 500;
}

.refresh-time {
  color: #999;
}

.message-items {
  margin-bottom: 20px;
}

.message-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 8px;
  border: 1px solid transparent;
}

.message-item:hover {
  background-color: #f8f9fa;
}

.message-item.unread {
  background-color: #fff3e0;
}

.message-indicator {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
}

.status-dot {
  width: 8px;
  height: 8px;
}

.status-dot.success {
  background-color: #4caf50;
}

.status-dot.warning {
  background-color: #ff9800;
}

.status-dot.info {
  background-color: #2196f3;
}

.status-dot.error {
  background-color: #f44336;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  line-height: 1.3;
}

.message-type {
  font-size: 14px;
  font-weight: 500;
  color: #666;
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  color: #999;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #666;
}

.loading-container p {
  margin-top: 10px;
  font-size: 14px;
}

/* 空消息状态 */
.empty-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #999;
}

.empty-message p {
  margin-top: 10px;
  font-size: 14px;
}

/* 消息详情弹框样式 */
.message-detail-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 15px;
}

.message-detail-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
}

.message-detail-content {
  padding: 20px 0;
}

.message-meta {
  display: flex;
  gap: 20px;
  font-size: 13px;
  color: #666;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.status {
  font-size: 12px;
  padding: 2px 8px;
  background-color: #e8f5e8;
  color: #4caf50;
}

.status.unread {
  background-color: #fff3e0;
  color: #ff9800;
}

.message-body {
  padding: 20px;
  background-color: #f8f9fa;
  margin-bottom: 20px;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 20px;
}

.message-text div {
  margin: 0 0 15px 0;
}

/* HTML content styling */
.message-text :deep(a) {
  color: #1976d2;
  text-decoration: none;
}

.message-text :deep(a:hover) {
  text-decoration: underline;
}

.message-text :deep(ul), .message-text :deep(ol) {
  padding-left: 20px;
  margin: 10px 0;
}

.message-text :deep(li) {
  margin-bottom: 5px;
}

.message-text :deep(p) {
  margin: 0 0 15px 0;
}

.message-text :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 10px 0;
}

.message-text :deep(h1), .message-text :deep(h2), .message-text :deep(h3),
.message-text :deep(h4), .message-text :deep(h5), .message-text :deep(h6) {
  margin: 15px 0 10px;
  font-weight: 600;
  line-height: 1.3;
}

.message-text :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 15px 0;
}

.message-text :deep(th), .message-text :deep(td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.message-text :deep(th) {
  background-color: #f2f2f2;
}

.message-text :deep(pre), .message-text :deep(code) {
  background-color: #f5f5f5;
  border-radius: 3px;
  padding: 2px 5px;
  font-family: monospace;
}

/* 消息加载状态 */
.message-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #666;
  gap: 10px;
}

.message-loading span {
  font-size: 14px;
}

/* 消息详情内容 */
.message-content-detail {
  margin-bottom: 20px;
}

.message-title-detail h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

/* Base styling for message text paragraphs is now handled by .message-text :deep(p) */

.message-footer {
  border-top: 1px solid #e9ecef;
  padding-top: 15px;
}

.platform-signature {
  font-size: 12px;
  color: #666;
  font-style: italic;
  margin: 0;
}

.message-id {
  font-size: 11px;
  color: #999;
  margin: 5px 0 0 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .enterprise-center {
    flex-direction: column;
  }
  
  .message-section {
    flex-direction: column;
    padding: 15px;
  }
  
  .message-categories {
    width: 100%;
  }
  
  .header-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style> 